package com.zhuangyuan.cloud.web.controller;

import com.zhuangyuan.cloud.data.entities.Category;
import com.zhuangyuan.cloud.data.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @RequestMapping(value = {"/categories","/category/index"})
    public ModelAndView index(HttpServletRequest request){
        prepareCategories();
        String parentId = request.getParameter("pid");
        List<Category> categories = null;
        if(!StringUtils.hasText(parentId)) {
            categories = categoryService.list(0);
        }else{
            categories = categoryService.children(parentId);
        }
        ModelAndView mv = new ModelAndView("/category/index");
        mv.addObject("categories",categories);
        return mv;
    }

    @GetMapping("/category/new/{parentId}")
    public ModelAndView addNewCategory(@PathVariable("parentId")String parentId) throws Exception {
        ModelAndView mv = new ModelAndView("/category/new");
        Category category = categoryService.get(parentId);
        if(category == null)
            throw new Exception(String.format("Category with id %s is not exits.",parentId));
        if(category.getLevel() >= 1){
            throw new Exception(String.format("This level can not add sub category. We not suggest make categories too deep."));
        }
        List<Category> children = categoryService.children(parentId);
        mv.addObject("children",children);
        mv.addObject("category",category);
        return mv;
    }

    @PostMapping("/category/createNew")
    @ResponseBody
    @Transactional
    public Map<String,Object> doCreate(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        String parentId = request.getParameter("parentId");
        String shortcut = request.getParameter("shortcut");
        Map<String,Object> map = new HashMap<>();
        boolean hasError = false;
        boolean success = false;
        if(StringUtils.hasText(parentId) && StringUtils.hasText(name) && StringUtils.hasText(shortcut)){
            Category category = categoryService.get(parentId);
            Category newCategory = new Category(name,category.getLevel()+1,shortcut,parentId);
            categoryService.add(newCategory);
            success = true;
        }else{
            hasError = true;
        }

        map.put("success",success);
        map.put("hasError",hasError);
        return map;
    }

    @PostMapping("/category/delete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> doDelete(HttpServletRequest request){
        String id = request.getParameter("id");
        boolean success = false;
        String msg = "";
        Map<String,Object> map = new HashMap<>();
        if(!StringUtils.hasText(id)){
            msg = "id can not be empty.";
            map.put("success",success);
            map.put("message",msg);
            return map;
        }
        //check has children
        boolean hasChild = categoryService.hasChild(id);
        if(hasChild){
            msg = "Can not delete this category, it has sub categories.";
            map.put("success",success);
            map.put("message",msg);
            return map;
        }
        //check has referenced by cate

        success = categoryService.delete(categoryService.get(id));
        map.put("success",success);
        return map;
    }



    private void prepareCategories(){
        Category p1 = new Category("热菜",0,"RC",null);
        List<Category> p1children = new ArrayList<>();
//        p1children.add(new Category("红烧臭鳜鱼",1,"HSCGY",p1.getId()));
//        p1children.add(new Category("红烧排骨",1,"HSPG",p1.getId()));
//        p1children.add(new Category("臭豆腐",1,"CDF",p1.getId()));
//        p1children.add(new Category("红烧鸭掌",1,"HSYZ",p1.getId()));
        categoryService.add(p1);
        categoryService.addAll(p1children);

        Category p2 = new Category("凉菜",0,"LC",null);
        List<Category> p2children = new ArrayList<>();
//        p2children.add(new Category("凉拌黄瓜",1,"LBHG",p2.getId()));
//        p2children.add(new Category("凉拌椿树头",1,"LBCST",p2.getId()));
        categoryService.add(p2);
        categoryService.addAll(p2children);

        Category p3 = new Category("汤",0,"T",null);
        List<Category> p3children = new ArrayList<>();
//        p3children.add(new Category("西红柿鸡蛋汤",1,"XHSJDT",p3.getId()));
//        p3children.add(new Category("老母鸡汤",1,"LMJT",p3.getId()));
        categoryService.add(p3);
        categoryService.addAll(p3children);

    }

    @RequestMapping("/category/detail/{code}")
    public String detail(@PathVariable(name = "code")String code, Model model){


        return "/category/detail";
    }

    @RequestMapping("/api/category/list")
    @ResponseBody
    public List<Category> list(){
        return categoryService.list();
    }

}
